package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.AnalysisByDay;
import com.tanhua.model.vo.UserAdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;


    public Integer queryCumulativeUsers() {
        return analysisMapper.queryCumulativeUsers();
    }

    public AnalysisByDay querySummary(Date now) {
        //5、根据当前时间查询AnalysisByDay数据
        LambdaQueryWrapper<AnalysisByDay> qw = Wrappers.<AnalysisByDay>lambdaQuery();
        qw.eq(AnalysisByDay::getRecordDate, DateUtil.format(now, "yyyy-MM-dd"));
        AnalysisByDay analysis = analysisMapper.selectOne(qw);
        if (analysis == null) {
            return new AnalysisByDay();
        }
        return analysis;
    }

    /**
     * 定时统计tb_log表中的数据，保存或者更新tb_analysis表
     * 1、查询tb_log表（注册用户数，登录用户数，活跃用户数，次日留存）
     * 2、构造Analysis对象
     * 3、保存或者更新
     */
    public void analysis() throws ParseException {
        //1、定义查询的日期
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesdayStr = DateUtil.yesterday().toString("yyyy-MM-dd");
        //2、统计数据-注册数量
        Integer regCount = logMapper.queryByTypeAndLogTime("0102", todayStr);
        //3、统计数据-登录数量
        Integer loginCount = logMapper.queryByTypeAndLogTime("0101", todayStr);
        //4、统计数据-活跃数量
        Integer activeCount = logMapper.queryByLogTime(todayStr);
        //5、统计数据-次日留存
        Integer numRetention1d = logMapper.queryNumRetention1d(todayStr, yesdayStr);
        //6、构造Analysis对象
        //7、根据日期查询数据
        QueryWrapper<AnalysisByDay> qw = new QueryWrapper<AnalysisByDay>();
        qw.eq("record_date", new SimpleDateFormat("yyyy-MM-dd").parse(todayStr));
        AnalysisByDay analysis = analysisMapper.selectOne(qw);
        //8、如果存在，更新，如果不存在保存
        if (analysis != null) {
            analysis.setNumRegistered(regCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.updateById(analysis);
        } else {
            analysis = new AnalysisByDay();
            analysis.setNumRegistered(regCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(todayStr));
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            analysisMapper.insert(analysis);
        }
    }


    public UserAdminVo users(Long sd, Long ed, Integer type) {

        // 时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatLast = new SimpleDateFormat("2020-MM-dd");

        UserAdminVo vo = new UserAdminVo();
        Long time = ed - sd;
        Long start = sd;

        List listCurrentYear = new ArrayList();
        List listLastYear = new ArrayList();


        if (type == 101) {
            if (time == (7 * 86400000)) {
                Long selectTime = time / 7;

                Integer register = 0;
                Integer registerLast = 0;
                for (int i = 1; i < 8; i++) {

                    Map map = new HashMap();
                    Map mapLast = new HashMap();

                    if (i == 1) {
                        register = logMapper.registerCount(format.format(sd), format.format(sd + selectTime), "0102");
                        map.put("title", i);
                        map.put("amount", register);
                        listCurrentYear.add(map);

                        registerLast = logMapper.registerLastCount(format.format(sd), format.format(ed));
                        mapLast.put("title", i);
                        mapLast.put("amount", registerLast);
                        listLastYear.add(mapLast);
                        start += selectTime;
                        continue;
                    }
                    // 新增用户数量
                    register = logMapper.registerCount(format.format(start), format.format(ed), "0102");
                    map.put("title", i);
                    map.put("amount", register);
                    listCurrentYear.add(map);

                    // 去年
                    registerLast = logMapper.registerLastCount(format.format(start), format.format(ed));
                    mapLast.put("title", i);
                    mapLast.put("amount", registerLast);
                    listLastYear.add(mapLast);

                    start += selectTime;
                    if (sd == ed) {
                        break;
                    }
                }
            } else {
                Long selectTime = time / 30;
                for (int i = 1; i < 30; i++) {
                    int title = new Random().nextInt(30);
                    // 新增用户数量
                    Integer register = logMapper.registerCount(format.format(sd), format.format(start), "0102");
                    Map map = new HashMap();
                    map.put("title", title);
                    map.put("amount", register);
                    listCurrentYear.add(map);

                    Integer lastRegister = logMapper.registerLastCount(format.format(sd), format.format(start));
                    Map mapLast = new HashMap();
                    mapLast.put("title", title);
                    mapLast.put("amount", lastRegister);
                    listLastYear.add(mapLast);

                    start += selectTime;
                    if (sd == ed) {
                        break;
                    }
                }

            }

        } else if (type == 102) {

            if (time == (7 * 86400000)) {
                Long selectTime = time / 10;

                Integer register = 0;
                Integer registerLast = 0;
                for (int i = 1; i < 11; i++) {
                    int title = new Random().nextInt(7) + 1;

                    Map map = new HashMap();
                    Map mapLast = new HashMap();


                    // 新增用户数量
                    register = logMapper.activeCount(format.format(start), format.format(ed));
                    map.put("title", title);
                    map.put("amount", register);
                    listCurrentYear.add(map);

                    // 去年
                    registerLast = logMapper.activeCount(formatLast.format(start), formatLast.format(ed));
                    mapLast.put("title", title);
                    mapLast.put("amount", registerLast);
                    listLastYear.add(mapLast);

                    start += selectTime;
                    if (sd == ed) {
                        break;
                    }
                }
            } else {
                Long selectTime = time / 40;
                for (int i = 1; i < 30; i++) {
                    int title = new Random().nextInt(40) + 1;
                    // 新增用户数量
                    Integer register = logMapper.activeCount(format.format(sd), format.format(start));
                    Map map = new HashMap();
                    map.put("title", title);
                    map.put("amount", register);
                    listCurrentYear.add(map);

                    Integer lastRegister = logMapper.activeCount(formatLast.format(sd), formatLast.format(start));
                    Map mapLast = new HashMap();
                    mapLast.put("title", title);
                    mapLast.put("amount", lastRegister);
                    listLastYear.add(mapLast);

                    start += selectTime;
                    if (sd == ed) {
                        break;
                    }
                }

            }

        } else if (type == 103) {

            String yesdayStr = DateUtil.yesterday().toString("yyyy-MM-dd");
//            String yesdayStr = "2021-06";

            if (time == (7 * 86400000)) {
                Long selectTime = time / 15;

                Integer register = 0;
                Integer registerLast = 0;
                for (int i = 1; i < 16; i++) {
                    int title = new Random().nextInt(16) + 1;

                    Map map = new HashMap();
                    Map mapLast = new HashMap();


                    register = logMapper.yestDay(format.format(start), format.format(ed), yesdayStr);
                    map.put("title", title);
                    map.put("amount", register);
                    listCurrentYear.add(map);

                    // 去年
                    registerLast = logMapper.yestDay(formatLast.format(start), formatLast.format(ed), yesdayStr);
                    mapLast.put("title", title);
                    mapLast.put("amount", registerLast);
                    listLastYear.add(mapLast);

                    start += selectTime;
                    if (sd == ed) {
                        break;
                    }
                }
            } else {
                Long selectTime = time / 40;
                for (int i = 1; i < 40; i++) {
                    int title = new Random().nextInt(40) + 1;
                    // 新增用户数量
                    Integer register = logMapper.yestDay(format.format(sd), format.format(start), yesdayStr);
                    Map map = new HashMap();
                    map.put("title", title);
                    map.put("amount", register);
                    listCurrentYear.add(map);

                    Integer lastRegister = logMapper.yestDay(formatLast.format(sd), formatLast.format(start), yesdayStr);
                    Map mapLast = new HashMap();
                    mapLast.put("title", title);
                    mapLast.put("amount", lastRegister);
                    listLastYear.add(mapLast);

                    start += selectTime;
                    if (sd == ed) {
                        break;
                    }
                }

            }

        }

        // 封装返回数据
        vo.setThisYear(listCurrentYear);
        vo.setLastYear(listLastYear);
        return vo;
    }


}
